package com.octo.captcha.image;

import com.octo.captcha.Captcha;

import javax.imageio.ImageIO;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public abstract class ImageCaptcha implements Captcha {
    private Boolean hasChallengeBeenCalled;
    protected String question;
    protected transient BufferedImage challenge;

    public ImageCaptcha() {

    }

    protected ImageCaptcha(String question, BufferedImage challenge) {
        this.hasChallengeBeenCalled = Boolean.FALSE;
        this.challenge = challenge;
        this.question = question;
    }

    @Override
    public final String getQuestion() {
        return this.question;
    }

    @Override
    public final Object getChallenge() {
        return this.getImageChallenge();
    }

    public final BufferedImage getImageChallenge() {
        this.hasChallengeBeenCalled = Boolean.TRUE;
        return this.challenge;
    }

    @Override
    public final void disposeChallenge() {
        this.challenge = null;
    }

    @Override
    public Boolean hasGetChalengeBeenCalled() {
        return this.hasChallengeBeenCalled;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        if (this.challenge != null) {
            ImageIO.write(this.challenge, "png", new MemoryCacheImageOutputStream(out));
        }

    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();

        try {
            this.challenge = ImageIO.read(new MemoryCacheImageInputStream(in));
        } catch (IOException var3) {
            if (!this.hasChallengeBeenCalled.booleanValue()) {
                throw var3;
            }
        }

    }
}